# -*- coding: utf-8 -*-
# @Date：2024/7/19 23:05:16
# @Author：CJiaの青姝
# @FileName：register
# @Editor：PyCharm2024
# @Remark：
import re
import random
from typing import Any
from typing_extensions import Self

from auths.models import Users
from auths.regular import password_reg, email_reg
from ninja import Router, Field, ModelSchema

from utils.cj_md5 import md5_encrypt
from utils.serializes import model_serialize_obj
from utils.cj_response import SuccessResponse, ErrorResponse

router = Router()


class RegisterSchemaIn(ModelSchema):
    code: str = Field(None, alias="captcha")

    def model_validate(
            cls,
            obj: Any,
            *,
            strict: bool | None = None,
            from_attributes: bool | None = None,
            context: Any | None = None,
    ) -> Self:
        if obj.code == '' or obj.code is None:
            return "验证不能为空", 400
        elif obj.username == '' or obj.username is None:
            return "用户名不能为空", 400
        elif obj.password == '' or obj.password is None:
            return "密码不能为空", 400
        elif obj.name == '' or obj.name is None:
            return "姓名不能为空", 400
        if not re.match(password_reg, obj.password):
            return "密码强度等级不够", 400
        elif not re.match(email_reg, obj.email):
            return "邮箱格式不正确", 400
        # 判断重复
        if Users.objects.filter(username=obj.username).exists():
            return "用户名已存在，请重新输入", 400
        if Users.objects.filter(email=obj.email).exists():
            return "邮箱已存在，请重新输入", 400
        # 返回请求数据
        return obj, 200

    class Config:
        model = Users
        model_fields = ["username", "password", "email", "mobile", "name", "gender"]


class RegisterSchemaOut(ModelSchema):
    class Config:
        model = Users
        model_exclude = ["password", "password_str"]


@router.post('/register', response=RegisterSchemaOut, auth=None, summary="用户注册")
def register(request, data: RegisterSchemaIn):
    message, code = data.model_validate(data)
    if code == 400:
        return ErrorResponse(msg=message)
    session_code = request.session.get("code", None)
    if session_code:
        if session_code == data.code:
            # 清除缓存验证码
            request.session.flush()
            # 转换数据
            data = data.dict()
            # 密码加密
            data['password_str'] = data['password']
            data['password'] = md5_encrypt(data['password'])
            data['id'] = random.randint(1000000000000, 9999999999999)
            data['user_type'] = 1
            del data['code']
            # 保存数据
            user_obj = Users.objects.create(**data)
            # 序列化
            result = model_serialize_obj(user_obj)
            # 返回结果
            return SuccessResponse(data=result, msg="注册成功")
        else:
            return ErrorResponse(msg="验证码错误，请重新输入")
    else:
        return ErrorResponse(msg="验证码不存在或已过期，请重新获取")
